<template>
    <router-link
            :to="'/article/' + article._id"
            class="flex articleItem"
    >
        <div class="flex flex-column align-start" style="flex-grow: 1">
            <div style="">
                <span class="articleInfo">{{article.author.nickname}}</span>
                <span class="articleInfo">{{article.createdAt|formatDate}}</span>
                <span class="articleInfo">{{article.category.cateName}}</span>
            </div>
            <router-link :to="'/article/' + article._id" class="article-title">{{ article.title }}</router-link>
            <el-button class="action-btn"
                       :type="userlikeArticles.includes(article._id) ? 'success' : 'info'"
                       @click.prevent="onclick_likeArticle(article)"
            >
                <i class="el-icon-thumb">{{ article.like }}</i>
            </el-button>
        </div>
        <img v-if="article.coverImage" :src="article.coverImage" width="60" height="60">
    </router-link>
</template>

<script>
    export default {
        name: "ArticleItem",
        props: ["article"],
        computed: {
            userlikeArticles() {
                return this.$store.state.user.likeArticles || [];
            }
        },
        methods: {
            async onclick_likeArticle(article) {
                let method = this.userlikeArticles.includes(article._id)
                    ? "delete"
                    : "put";
                let res = await this.$http[method]("/user/likeArticle/" + article._id);
                if (res.code == 0) {
                    // 这里是取巧的做法。实际应该管理内部状态用vuex
                    this.$store.dispatch("detail");
                    // this.getArticle();
                    if (method == "delete") {
                        this.article.like--
                    } else {
                        this.article.like++
                    }
                    this.$emit("click_likeArticle")
                    this.$message.success(res.message);
                }
            }
        }
    }
</script>

<style scoped lang="less">
    .articleItem {
        height: 120px;
        border-bottom: 1px solid rgba(178, 186, 194, 0.15);
        padding: 18px 24px;
    }

    .articleInfo {
        color: #b2bac2;
    }

    .article-title {
        color: #2e3135;
        margin: 6px 0 12px;
        font-weight: 600;
    }

    .article-title:hover {
        text-decoration: underline;
    }

    .action-btn {
        width: 45px;
        height: 24px;
        border: 1px solid #edeeef;
        padding: 0;
    }

    .articleInfo:not(:last-child):after {
        content: "·";
        margin: 0 .4em;
        color: #b2bac2;
    }
</style>
